import { execRemoteAPI } from "@/views/formgen/api/execRemoteAPI";
import { get, isArray } from "lodash-es";

export function useFormOption() {
  const getOptions = async (config: any) => {
    let finalOptions = config.options;
    if (config.optionsType && config.optionsType === 1) {
      try {
        if (!config.dynamicOptions.url) {
          return [];
        }
        const res = await execRemoteAPI.get<any>(config.dynamicOptions.url);
        const options = get(res, config.dynamicOptions.dataPath);
        if (options && isArray(options)) {
          const dyOptions = options.map((op: any) => {
            let other: any = {};
            if (config.dynamicOptions.childrenField) {
              other["children"] = get(op, config.dynamicOptions.childrenField);
            }
            return {
              value: get(op, config.dynamicOptions.valueField),
              label: get(op, config.dynamicOptions.labelField),
              ...other
            };
          });
          finalOptions = dyOptions;
        }
      } catch (error) {
        console.error("Error fetching dynamic options:", error);
      }
      //  如果是字典值 从字字典接口获取
    } else if (config.optionsType && config.optionsType === 2) {
      try {
        const dictRes = await execRemoteAPI.get<any>(`/system/dict/data/type/${config.dictOptionType}`);
        finalOptions = dictRes.data.map((op: any) => ({
          value: op.dictValue,
          label: op.dictLabel
        }));
      } catch (error) {
        console.error("Error fetching dictionary options:", error);
      }
    } else if (config.optionsType && config.optionsType === 3) {
      try {
        const dictRes = await execRemoteAPI.get<any>(`/user/form/data/field/data/list`, {
          formKey: config.linkFormKey,
          formItemId: config.linkFormItemId
        });
        finalOptions = dictRes.data.map((op: any) => ({
          value: op,
          label: op
        }));
      } catch (error) {
        console.error("Error fetching dictionary options:", error);
      }
    }
    return finalOptions;
  };
  return {
    getOptions
  };
}
